import React, { useState, useContext } from "react";


// 创建公用数据
// 1.创建类型
type ContextType = {
    dataObj: { name: string, age: number }, setDataObj: React.Dispatch<React.SetStateAction<{
        name: string;
        age: number;
    }>>
};
const AppContext = React.createContext<ContextType>({} as ContextType);

export const APPContextWrapper = (props: any) => {
    const [dataObj, setDataObj] = useState({ name: "lkx", age: 16 });
    return <AppContext.Provider value={{ dataObj, setDataObj }}>
        {props.children}
    </AppContext.Provider>
}

// 子组件
export const Son1 = () => {
    const { dataObj, setDataObj } = useContext(AppContext);
    return (
        <>
            <h2>第一个子节点</h2>
            <h3>父组件的对象的姓名：{dataObj.name};年龄：{dataObj.age}</h3>
            <button onClick={() => {
                setDataObj(e => {
                    return { ...e, name: "lkx1" }
                })
            }}>修改父组件的名称</button>
            <button onClick={() => {
                setDataObj(e => {
                    return { ...e, age: e.age + 1 }
                })
            }}>修改父组件的年龄</button>
        </>
    )
}

// 子组件2

export const Son2 = () => {
    const { dataObj, setDataObj } = useContext(AppContext);
    return (
        <>
            <h2>第二个子组件</h2>
            <h3>父组件的对象的姓名：{dataObj.name};年龄：{dataObj.age}</h3>
            <button onClick={() => {
                setDataObj({ name: "lkx", age: 16 })
            }}>重置</button>
            <Son3></Son3>
        </>
    )
}


export const Son3 = () => {
    const { dataObj, setDataObj } = useContext(AppContext);
    return(
        <>
            <h3>这是孙子组件</h3>
            <h3>父组件的对象的姓名：{dataObj.name};年龄：{dataObj.age}</h3>
            <button onClick={()=>{
                setDataObj(e=>{
                    return {...e,age:e.age-1}
                })
            }}>递减</button>
        </>
    )
}

export const DemoTest = () => {
    return (
        <>
            <h1>Demo Test</h1>
            <APPContextWrapper>
                <Son1></Son1>
                <Son2></Son2>
            </APPContextWrapper>
        </>
    )
}